package controller;

import entity.User;
import service.IUser;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置客户端的编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        // 1.接受请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 获取session
        HttpSession session = request.getSession();

        //判断账户是否为空
        if(username == null || "".equals(username.trim())){
            //提示用户信息
            // request.setAttribute("msg", "账号不能为空！");
            session.setAttribute("msg", "账号不能为空！");
            //请求跳转到login，jsp
            request.getRequestDispatcher("Login.jsp").forward(request, response);
            return;
        }

        //判断密码是否为空
        if(password == null || "".equals(password.trim())){
            //提示用户信息
            // request.setAttribute("msg", "密码不能为空！");
            session.setAttribute("msg", "密码不能为空！");
            //请求跳转到login，jsp
            request.getRequestDispatcher("Login.jsp").forward(request, response);
            return;
        }

        // 2.创建Service对象
        IUser userservice = new UserServiceImpl();

        // 3. 调用Service对象的checkStudent()方法用户进行验证
        User user = userservice.checkUser(username, password);

        // 4.验证没通过，则跳转到登陆页面，让用户重新输入信息，此时页面给出提示信息
        if (user == null){

            session.setAttribute("msg", "账户或密码错误");
            response.sendRedirect(request.getContextPath()+"/Login.jsp");
            return;
        }
        // 5.验证通过，则跳转到系统页面LoginSuccess.jsp
        session.setAttribute("username", username);

        response.sendRedirect(request.getContextPath()+"/LoginSuccess.jsp");
    }
}
